package com.jhy.suixianglu.daima20230117;

/**
 * kmp解法
 * <p>
 * 字符串在另外字符串里面是否出现过
 */
public class RepeatedSubstringPattern {
    public static boolean repeatedSubstringPattern(String s) {
        // 声明一个next数组
        int[] next = new int[s.length()];
        // 初始化
        getNext(next, s);
        System.out.println(next.toString());
        int temp = 0;
        for (int i = 0; i < next.length; i++) {
            if (next[i] > temp) {
                temp = i;
            }
        }
        if (s.length() % (s.length() - temp ) == 0) {
            return true;
        }
        return false;
    }

    private static void getNext(int[] next, String s) {
        int pre = 0;
        next[pre] = 0;
        for (int suf = 1; suf < s.length(); suf++) {
            // 前后缀不相等
            while (pre > 0 && s.charAt(pre) != s.charAt(suf)) {
                pre = next[pre - 1];
            }
            // 前后缀相等
            if (s.charAt(suf) == s.charAt(pre)) {
                pre++;
            }
            // 更新next
            next[suf] = pre;
        }
    }

    public static void main(String[] args) {
        String s = "abab";
        boolean b = repeatedSubstringPattern(s);
        System.out.println(b);

    }

}
